<template>
	<view :style="themeColor">
		<view class="page">
			<view
				class="flex flex-direction flex-wrap align-stretch justify-center benben-position-layout flex helpFeedback_flex_0"
				:style="{height:(88+StatusBarRpx)+'rpx',paddingTop:StatusBarRpx+'rpx', }">
				<view class='flex flex-wrap align-stretch justify-between helpFeedback_fd0_0'>
					<view class='flex flex-wrap align-center helpFeedback_fd0_0_c0' @tap.stop="handleJumpDiy" data-type="back"
						data-url="1">
						<text class='fu-iconfont2  helpFeedback_fd0_0_c0_c0'>&#xe794;</text>
					</view>
					<view class='flex flex-wrap align-center'>
						<text class='helpFeedback_fd0_0_c1_c0'>设置页</text>
					</view>
					<view class='flex align-center justify-end helpFeedback_fd0_0_c2'>
					</view>
				</view>
			</view>
			<view :style="{height: (88+StatusBarRpx)+'rpx'}"></view>

			<view class='flex flex-wrap align-center justify-between user_fd1_0' @tap.stop="pickerDiy1683966462102=true">
				<!--  -->
				<text class='user_fd1_2_c0'>性别111</text>
				<input class='flex-sub user_fd1_1_c1' type="text" confirm-type="done" :maxlength="30"
					placeholder-style="color:rgba(102, 102, 102, 1);font-size:32rpx" v-model="sex_label" :disabled="true" />
				<text class='fu-iconfont2  user_fd1_3_c2'>&#xE78E;</text>
			</view>
			<benben-picker ref="benbenWritePickerCodepicker2" :visible.sync="pickerDiy1683966462102" :label.sync='sex_label'
				:value.sync='deviceInfo.sex_value' :options='sex_options' mode='selector' :mask-show='true' :timeout='true'
				:picker-height='88' default-type='value' :default-props='{"label":"name","value":"value"}'>
				<template #picker-header>
					<view class='flex flex-wrap align-center justify-between user_picker2_0'>
						<text class='user_picker2_0_c0' @tap="$refs.benbenWritePickerCodepicker2.cancel()">取消</text>
						<text class='user_picker2_0_c1'>选择性别</text>
						<text class='user_picker2_0_c2' @tap="$refs.benbenWritePickerCodepicker2.pickerConfirm()">确定</text>
					</view>
				</template>
			</benben-picker>
			<text @tap="getDeviceId">{{title}}</text>
			<view :style="{height: '130rpx'}"></view>


		</view>
	</view>
</template>
<script>
	import {
		validate
	} from '@/common/utils/validate.js'
	export default {
		components: {},


		data() {
			return {
				"pickerDiy1683966462102": false,

				"sex_options": [{
					"name": "男",
					"value": "1"
				}, {
					"name": "女",
					"value": "2"
				}, {
					"name": "保密",
					"value": "3"
				}],

				"sex_label": "",
				deviceInfo: {
					"sex_value": "",
				},
				title: 'Hello',
				deviceId: '',
				onlineState: '', //设备是否在线
				serviceId: '',
				writeCharacteristicId: "", // 可写特征值
				notifyCharacteristicId: "", //监听特征值
			};
		},
		computed: {
			themeColor() {
				return this.$store.getters.themeColor
			},

		},
		watch: {},
		onLoad(options) {
			// if (!option.state) {
			// 	uni.removeStorageSync("deviceId");
			// }

		},
		onUnload() {

		},
		onReady() {
			this.getDeviceId()
		},
		onShow() {

		},
		onHide() {

		},
		onResize() {

		},
		onPullDownRefresh() {

		},
		onReachBottom(e) {

		},
		onPageScroll(e) {

		},
		methods: {

			getDeviceId() {
				console.log('11111111')
				// 获取缓存中的 deviceId
				const deviceId = uni.getStorageSync("deviceId");
				// 判断 deviceId 是否为空
				if (deviceId) {
					// 如果 deviceId 不为空，进行赋值操作
					console.log("从缓存中获取的 deviceId:", deviceId);
					this.deviceId = deviceId;
					this.onlineState = "在线";
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success: (res) => {
							console.log("设备服务列表:", res.services);
							const serviceId = res.services[2].uuid; // 获取可用的服务id
							this.serviceId = serviceId;
							this.getBLECharacteristics(deviceId, this.serviceId);
						},
						fail: (err) => {
							console.error("获取服务失败", err);
						}
					});
				} else {
					console.log("缓存中没有 deviceId");
				}
			},
			//获取设备的特征值
			getBLECharacteristics(deviceId, serviceId) {
				console.log(serviceId, 'serviceId')
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success: (res) => {
						console.log("特征值列表:", res.characteristics);
						this.writeCharacteristicId = res.characteristics[0]
							.uuid; // 记录可写特征值 -下发的特征值UUlD:6e400002-af50-59bc-0446-b58fc848c63b
						let readId = res.characteristics[1].uuid //收取数据的特征值6e400003-af50-59bc-0446-b58fc848c63b
						// this.writeCharacteristicId='0000ffe1-0000-1000-8000-00805f9b34fb'
						// let readId='0000ffe1-0000-1000-8000-00805f9b34fb'
						console.log(this.writeCharacteristicId, '下发可写的特征值UUlD:6e400002')
						console.log(readId, '读取数据的特征值UUlD:6e400003')
						const data = "A7000200060100097A";
						this.sendData(deviceId, serviceId, this.writeCharacteristicId, data) //发送数据
						this.startNotify(deviceId, serviceId, readId); //监听特征值
					},
					fail: (err) => {
						console.error("获取特征值失败", err);
					}
				});
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			// 将16进制的内容转成我们看得懂的字符串内容
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					console.log("存在非法字符!");
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			},
			//监听设备返回的数据
			startNotify(deviceId, serviceId, notifyId) {
				uni.notifyBLECharacteristicValueChange({
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: notifyId,
					state: true,
					success: (result) => {
						// console.log("notifyId：",notifyId)
						console.log("开启监听成功", result);
						this.read(deviceId, serviceId, notifyId)
						uni.onBLECharacteristicValueChange((res) => {
							console.log("res：", res);
							let resHex = this.ab2hex(res.value)
							let result = this.hexCharCodeToStr(resHex)
							console.log("收到 JSON 数据:", String(result))
						});
					},
					fail: (err) => {
						// console.log("notifyId：",notifyId)
						console.error("开启监听失败", err);
					}
				});
			},
			sendData(deviceId, serviceId, characteristicId, data) {
				try {
					// 将 16 进制字符串转换为字节数组
					let byteArray = this.hexStringToBytes(data);
					console.log("发送 byteArray:", byteArray);

					// 将 Uint8Array 转换为 ArrayBuffer
					let buffer = byteArray.buffer; 

					// 发送数据
					uni.writeBLECharacteristicValue({
						deviceId: deviceId,
						serviceId: serviceId,
						characteristicId: characteristicId,
						value: buffer, // 需要传 ArrayBuffer
						success: (res) => {
							console.log("发送成功", res);
							this.read(deviceId, serviceId, characteristicId);
						},
						fail: (err) => {
							console.error("发送失败", err);
						}
					});
				} catch (error) {
					console.error("转换错误", error);
				}
			},

			// 将16进制字符串转换为字节数组
			hexStringToBytes(hexString) {
				let result = [];
				for (let i = 0; i < hexString.length; i += 2) {
					result.push(parseInt(hexString.substr(i, 2), 16));
				}
				return new Uint8Array(result);
			},
			read(deviceId, serviceId, characteristicId) {
				uni.readBLECharacteristicValue({
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: characteristicId,
					success(res) {
						console.log(res, "read指令发送成功");
					},
					fail(err) {
						console.error(err, "read指令发送失败");
					}
				})
			}



			// gobangzhuInfo(aid, title) {
			// 	uni.navigateTo({
			// 		url: `/pages/my/helpDetail/helpDetail?aid=${aid}&title=${title}`
			// 	})
			// },
		}
	};
</script>
<style lang="scss" scoped>
	.page {
		width: 100vw;
		overflow-x: hidden;
		min-height: calc(100vh - var(--window-bottom));
		background: var(--benbenbgColor1);
		background-size: 100% auto;
	}

	.helpFeedback_flex_0 {
		border-bottom: 1px solid rgba(238, 238, 238, 1);
		background: #fff;
		width: 750rpx;
		height: 88rpx;
		overflow: hidden;
		z-index: 10;
		top: 0rpx;
		background-size: 100% auto !important;
	}

	.helpFeedback_fd0_0_c2 {
		padding: 0rpx 0rpx 0rpx 0rpx;
		width: 100rpx;
	}

	.helpFeedback_fd0_0_c1_c0 {
		font-size: 36rpx;
		font-weight: 500;
		color: var(--benbenFontColor0);
	}

	.helpFeedback_fd0_0_c0_c0 {
		font-size: 36rpx;
		font-weight: 400;
		color: #333;
	}

	.helpFeedback_fd0_0_c0 {
		width: 100rpx;
	}

	.helpFeedback_fd0_0 {
		padding: 0rpx 32rpx 0rpx 32rpx;
		line-height: 88rpx;
	}

	.helpFeedback_flex_1 {
		font-size: 32rpx;
	}

	.user_fd1_0 {
		border-bottom: 1px solid #eee;
		padding: 32rpx 0rpx 32rpx 0rpx;
	}

	.user_picker2_0_c2 {
		color: var(--benbenFontColor0);
		font-size: 32rpx;
		font-weight: 400;
	}

	.user_picker2_0_c1 {
		color: var(--benbenFontColor0);
		font-size: 32rpx;
		font-weight: 500;
	}

	.user_picker2_0_c0 {
		color: rgba(153, 153, 153, 1);
		font-size: 32rpx;
		font-weight: 400;
	}

	.user_picker2_0 {
		border-bottom: 1px solid #eee;
		background: #fff;
		padding: 0rpx 32rpx 0rpx 32rpx;
		line-height: 88rpx;
		border-radius: 25rpx 25rpx 0rpx 0rpx;
		background-size: 100% auto !important;
	}

	.user_fd1_2_c0 {
		font-size: 32rpx;
		font-weight: 400;
		color: rgba(51, 51, 51, 1);
	}

	.user_fd1_1_c1 {
		line-height: 45rpx;
		font-size: 32rpx;
		font-weight: 400;
		color: #333;
		text-align: right;
		margin: 0rpx 0rpx 0rpx 48rpx;
	}

	.user_fd1_3_c2 {
		font-size: 28rpx;
		margin: 0rpx 0rpx 0rpx 14rpx;
	}

	.helpFeedback_fd1_0_c0_c1 {
		font-size: 26rpx;
		color: rgba(153, 153, 153, 1);
	}

	.helpFeedback_fd1_0_c0_c0 {
		font-size: 36rpx;
		color: var(--benbenFontColor0);
		font-weight: 400;
		line-height: 50rpx;
	}

	.helpFeedback_fd1_0_c0 {
		border-bottom: 1px solid #eee;
		padding: 32rpx 0rpx 32rpx 0rpx;
		margin: 0rpx 32rpx 0rpx 32rpx;
	}

	.helpFeedback_fd1_0 {
		margin: 0rpx 0rpx 180rpx 0rpx;
	}

	.helpFeedback_flex_2 {
		width: 750rpx;
		height: 130rpx;
		overflow: hidden;
		z-index: 10;
		bottom: 0;
	}

	.helpFeedback_fd2_0_c1 {
		color: var(--benbenFontColor3);
		font-size: 32rpx;
		font-weight: 500;
	}

	.helpFeedback_fd2_0_c0 {
		width: 32rpx;
		height: 32rpx;
		margin: 0rpx 18rpx 0rpx 0rpx;
	}

	.helpFeedback_fd2_0 {
		background: #F06600;
		border-radius: 90rpx 90rpx 90rpx 90rpx;
		width: 638rpx;
		height: 88rpx;
	}
</style>